# encoding:utf-8
import requests
import base64
# 百度智能云官网获取 ak 和 sk
ak = "89tIu4OxR6SfT4UiGymEBWcH"
sk = "3XKExo96fR85BsacpxAuA4X3mLEYKIhu"

# 获取 token 令牌
def getToken():
    # client_id 为官网获取的AK， client_secret 为官网获取的SK
    host = f'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={ak}&client_secret={sk}'
    response = requests.get(host)
    if response:
        # print(response.json()['access_token'])
        return response.json()['access_token']
    else:
        print("获取token失败")
        return "error"

#图片转码成base_64
def img2base64(path):
    with open (path,'rb') as fp:
        base_64=base64.b64encode(fp.read())
        return base_64

def base64_2img(base_64,file_name):
    with open(file_name,'wb') as fp:
        fp.write(base64.b64decode(base_64))


def get_person_num(path):
    try:
        request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/body_num"
        # 二进制方式打开图片文件
        img = img2base64(path)
        params = {
            "image":img,
            "show":"false" #true显示照片
        }
        access_token = getToken()
        request_url = request_url + "?access_token=" + access_token
        headers = {'content-type': 'application/x-www-form-urlencoded'}
        response = requests.post(request_url, data=params, headers=headers)
        res = response.json()
        # img=res['image']
        # base64_2img(img,'new.jpg')
        return res["person_num"]
    except:
        print("流量统计失败",path)
        return -1
# print("ok",get_person_num('E:/Code/pycharm/djangoProject/static/img/flow_1.jpg'))